package router

import (
	"fmt"
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"go-vue-blog-sever/config"
	"go-vue-blog-sever/handler"
	"go-vue-blog-sever/service/admin"
)

type R interface {
	Run() error
}

type Ro struct {
	addr string
	port string
	rou  *gin.Engine
}

func (rr *Ro) Run() error {
	if rr.addr == "" || rr.port == "" {
		return fmt.Errorf("addr or port is empty")
	}
	return rr.rou.Run(rr.addr + ":" + rr.port)
}

func NewRouter(config *config.RoutConfig) *Ro {
	if config.Log && config.Cor {
		return &Ro{
			rou:  gin.Default(),
			addr: config.Addr,
			port: config.Port,
		}
	}
	return &Ro{
		rou:  gin.New(),
		addr: config.Addr,
		port: config.Port,
	}
}

func (rr *Ro) Router() R {
	router := rr.rou
	router.Static("/static", "./stack")

	config2 := cors.DefaultConfig()
	config2.AllowHeaders = []string{
		"Authorization",
		"Access-Control-Allow-Headers",
		"Access-Control-Allow-Origin",
		"Access-Control-Allow-Methods",
		"Content-Type",
		"Content-Length",
		"Accept-Encoding",
		"X-CSRF-Token",
		"Accept-Language",
		"Accept-Encoding",
		"Cookie",
	} // 允许的请求头
	config2.AllowOrigins = []string{"http://localhost:3001"} // 允许的域名或 IP 地址
	config2.AllowCredentials = true
	config2.AddAllowMethods("OPTIONS") // 同意欲请求
	router.Use(cors.New(config2))
	api := router.Group("api")
	{
		ad := api.Group("admin")
		{
			ad.POST("/login", admin.UserLogin)
			ad.POST("/logout", admin.UserLogout)
			ad.POST("/blog/list", handler.ValidTokens(), admin.GetBlog)
			cateType := ad.Group("/cate")
			{
				cateType.GET("/list", handler.ValidTokens(), admin.GetCateType)
				cateType.GET("/all", handler.ValidTokens(), admin.GetAllCateType)
			}
		}
	}
	return &Ro{
		addr: rr.addr,
		port: rr.port,
		rou:  router,
	}
}
